package com.fz.us.oa.web.controller.main;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.base.utils.EntityConfig;
import com.fz.us.admin.base.utils.LogUtil;
import com.fz.us.admin.company.bean.EnumManage;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.*;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.oa.core.entity.com.CommonModel;
import com.fz.us.oa.core.entity.com.ModulePower;
import com.fz.us.oa.core.entity.com.NoticeTest;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.CommonModelService;
import com.fz.us.oa.core.service.com.ModulePowerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 控制器 - 主页
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-01 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main")
public class IndexController extends BaseController {

    private static final long serialVersionUID = -3387066815980698553L;

    @Autowired
    private ProcessBriefService processBriefService;
    @Autowired
    private StepBriefService stepBriefService;
    @Autowired
    private CommonConfigService commonConfigService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private TaskFlowService taskFlowService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private CommonModelService commonModelService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private ModulePowerService modulePowerService;

    private static final EntityConfig entityConfig  = new EntityConfig();

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(@CurrentUser User user, Model model) {

        //首页权限判断
        boolean isPass=false;
        Admin admin=adminService.get(user.getAdminId());
        if(admin!=null){
            if(EnumManage.AccountTypeEnum.Manager.equals(admin.getAccountTypeEnum())){
                isPass=true;
                model.addAttribute("manager",true);
            }else{
                ModulePower modulePower=modulePowerService.getModulePowerPassByUser(user);
                if(modulePower!=null){
                    isPass=true;
                    model.addAttribute("modulePower",modulePower);
                }
            }
        }

        //待办数量
        int numTodo=taskEntityService.getInfoByEditors(new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed}, user.getId()).size();
        int numDraft=taskEntityService.getInfoByDraft(FlowEnum.ProcessState.Draft, user).size();

        model.addAttribute("numTodo", numTodo);
        model.addAttribute("numDraft", numDraft);
        model.addAttribute("isPass", isPass);
        model.addAttribute("user", user);
        return "/main/index";
    }

    /**
     * 计算操作者可选身份
     * @return
     */
    @RequestMapping(value = "dutyDlg", method = RequestMethod.GET)
    public Object dutyDlg(@CurrentUser User user,String entityName,String keyId){
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("state","400");
        if(StringUtils.isEmpty(entityName)){
            return ajaxJson(rMap);
        }
        ProcessBrief processBrief = processBriefService.getInfoByTableKey(entityName);
        if(processBrief == null ){
            return ajaxJson(rMap);
        }
        StepBrief stepBrief = null;
        List<Duty> dutyList = null;
        if(StringUtils.isEmpty(keyId)){
            stepBrief = stepBriefService.getInfoByStepNo(processBrief, 1);
            dutyList = commonConfigService.findDutyByConfig(stepBrief.getCommonConfig().getId());
        }else{
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            if(taskEntity == null){
                stepBrief = stepBriefService.getInfoByStepNo(processBrief, 1);
            }else{
                stepBrief = stepBriefService.getInfoByStepNo(processBrief, taskEntity.getStepNo());
            }
            dutyList = commonConfigService.findDutyByConfig(keyId, entityName, stepBrief.getCommonConfig().getId());
            //获取上一步的特殊职责
            if(StringUtils.isNotEmpty(stepBrief.getSpecialType())){
                List<TaskFlow> taskFlowList = taskFlowService.getInfoByTaskStepBrief(taskEntity, stepBrief);
                for(TaskFlow taskFlow: taskFlowList){
                    Set<Duty> specialDutySet = stepBriefService.findSpecialByDuty(stepBrief, taskFlow.getDuty());
                    dutyList.addAll(specialDutySet);
                }
            }
        }
        if(stepBrief == null){
            return ajaxJson(rMap);
        }
        dutyList.retainAll(dutyService.getDutys(user));
        Set<Duty> dutySet = Sets.newHashSet();
        dutySet.addAll(dutyList);
        Map<String, Object> data = new HashMap<String, Object>();
        List<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();

        for(Duty duty :dutySet){
            rMap = Maps.newHashMap();
            rMap.put("name",duty.getPower().getDepartment().getName()+"-"+duty.getPower().getPost().getName());
            rMap.put("id",duty.getId());
            rMap.put("checked","");
            dataRows.add( rMap);
        }
        data.put("data",dataRows);
        data.put("size",dataRows.size());
        data.put("state","1");
        data.put("keyId", keyId);
        data.put("entityName", entityName);
        return ajaxJson(data);
    }

    /**
     * 获取身份数据
     */
    @RequestMapping(value = "getDutyDlg", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String getDutyDlg(@CurrentUser User user, Model model,String entityName,String keyId) {

        ProcessBrief processBrief = processBriefService.getInfoByTableKey(entityName);

        StepBrief stepBrief = null;
        List<Duty> dutyList = null;
        if(StringUtils.isEmpty(keyId)){
            stepBrief = stepBriefService.getInfoByStepNo(processBrief, 1);
            dutyList = commonConfigService.findDutyByConfig(stepBrief.getCommonConfig().getId());
        }else{
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            if(taskEntity == null){
                stepBrief = stepBriefService.getInfoByStepNo(processBrief, 1);
            }else{
                stepBrief = stepBriefService.getInfoByStepNo(processBrief, taskEntity.getStepNo());
            }
            dutyList = commonConfigService.findDutyByConfig(keyId, entityName, stepBrief.getCommonConfig().getId());
            //获取上一步的特殊职责
            if(StringUtils.isNotEmpty(stepBrief.getSpecialType())){
                List<TaskFlow> taskFlowList = taskFlowService.getInfoByTaskStepBrief(taskEntity, stepBrief);
                for(TaskFlow taskFlow: taskFlowList){
                    Set<Duty> specialDutySet = stepBriefService.findSpecialByDuty(stepBrief, taskFlow.getDuty());
                    dutyList.addAll(specialDutySet);
                }
            }
        }
        dutyList.retainAll(dutyService.getDutys(user));
        model.addAttribute("entityName",entityName);
        model.addAttribute("keyId",keyId);
        model.addAttribute("dutyList",dutyList);
        return "/main/getDutyDlg_input";
    }

    /**
     * 选择当前人常用列表数据
     */
    @RequestMapping(value = "getAllModel", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String getAllModel(@CurrentUser User user, Model model,String mids) {

        List<Map<String,Object>> mapList = entityConfig.getAllProperties();
        Map<String,Object> rmap;
        model.addAttribute("mids",mids);
        if (StringUtils.isNotBlank(mids)) {
            String[] pids = StringUtils.split( mids,",");
            ArrayList<Map<String,Object>> models = new ArrayList<Map<String,Object>>();
            for (String pid : pids) {
                for(Map map:mapList){
                    if(StringUtils.equals(pid, map.get("key").toString())){
                        rmap = Maps.newHashMap();
                        rmap.put("key", map.get("key").toString());
                        rmap.put("value", map.get("value").toString());
                        models.add(rmap);
                        break;
                    }
                }
            }
            model.addAttribute("selectedModels", models);
        }
        return "/main/company/getAllModel";
    }

    /**
     * 常用模块列表
     */
    @RequestMapping(value = "model/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {

        ModulePower modulePower=modulePowerService.getModulePowerPassByUser(user);
        List<String> entityNameList=new ArrayList<String>();
        if(modulePower!=null){
            entityNameList=Arrays.asList(modulePower.getEntityName().split(","));
        }

        List<Map<String,Object>> mapList = entityConfig.getAllProperties();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rmap;
        for(Map map:mapList){
            if(entityNameList.contains(map.get("key").toString())){//只添加有权限的表单
                rmap = Maps.newHashMap();
                rmap.put("id", map.get("key").toString());
                rmap.put("name", map.get("value").toString());
                dataRows.add(rmap);
            }
        }
        data.put("dataRows", dataRows);

        return data;
    }

    /**
     * 初始加载当前人常用列表数据
     */
    @RequestMapping(value = "getCommonModel", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String getCommonModel(@CurrentUser User user, Model model) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("user", user);
        List<CommonModel> commonModelList1 = commonModelService.getList(params);

        ModulePower modulePower=modulePowerService.getModulePowerPassByUser(user);
        List<String> entityNameList=new ArrayList<String>();
        if(modulePower!=null){
            entityNameList=Arrays.asList(modulePower.getEntityName().split(","));
        }

        List<CommonModel> commonModelList=new ArrayList<CommonModel>();
        for(CommonModel commonModel:commonModelList1){
            if(entityNameList.contains(commonModel.getKey1())){
                commonModelList.add(commonModel);
            }
        }

        model.addAttribute("commonModelList",  commonModelList);
        return "/main/company/getCommonModel";
    }
    /**
     * 保存当前人常用列表数据
     */
    @RequestMapping(value = "saveCommonModel", method = RequestMethod.POST, produces = MediaType.TEXT_HTML_VALUE)
    public Object saveCommonModel(@CurrentUser User user, Model model, @RequestParam(required=false) String keys,  @RequestParam(required=false) String vals) {

        if(StringUtils.isNotEmpty(keys)){
           commonModelService.delCommonModel(user);
           String[]  keyArr =  keys.split(",");
           String[]  valArr =  vals.split(",");
           for(int i=0; i<keyArr.length; i++){
                CommonModel commonModel = new CommonModel();
                commonModel.setKey1(keyArr[i]);
                commonModel.setVal1(valArr[i]);
                commonModel.setUser(user);
                commonModel.setState(BaseEnumManager.StateEnum.Enable);
                commonModelService.save(commonModel);
           }
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("state", "1");
        return ajaxJson(rMap);
    }


}
